#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <string>
#include <unistd.h>
#include <pthread.h>
#include <memory>
#include "Thread.hpp"

using namespace std;

 //添加__thread，可以将一个内置类型设置为线程局部存储

 __thread int g_val = 100;
std::string changeId(const pthread_t &thread_id)
 {
     char tid[128];
     snprintf(tid, sizeof(tid), "0x%x", thread_id);
     return tid;
 }

 void *start_routine(void *args)
 {
     std::string threadname = static_cast<const char *>(args);
     // pthread_detach(pthread_self()); //设置自己为分离状态

     int cnt = 5;
     while (true)
     {
         //std::cout << threadname << " running ... : " << changeId(pthread_self()) <<" g_val: "<< g_val << " &g_val: " << &g_val << std::endl;
         std::cout << threadname << " running ... : " << pthread_self()<<" g_val: "<< g_val << " &g_val: " << &g_val << std::endl;
         
         sleep(1);
         g_val++;
     }

     return nullptr;
 }

int tickets=g_val;
void *getTicket(void *args)
{
    // other code
    std::string username = static_cast<const char *>(args);
    // ThreadData *td = static_cast<ThreadData *>(args);
    
    while (true)
    {
            
            if (tickets > 0)
            {
                usleep(1254); // 1秒 = 1000毫秒 = 1000 000 微妙 = 10^9纳秒
                // 值得抢
                //  std::cout << td->threadname_ << " 正在进行抢票: "<< tickets << std::endl;
                std::cout << username << " 正在进行抢票: " << tickets << std::endl;
                // 用这段时间来模拟真实的抢票要花费的时间
                tickets--;
                // pthread_mutex_unlock(&lock);
            }
            else
            {
                // pthread_mutex_unlock(&lock);
                break;
            }
        
        // 抢完票就完了了吗？当然不是
           //usleep(1000); // 形成一个订单给用户
    }

    // other code

    return nullptr;
}

int main()
{
    
   //std::string main_id = changeId(pthread_self());
    /*pthread_t t1, t2, t3, t4;
    pthread_create(&t1, nullptr, getTicket, (void *)"thread 1");
    pthread_create(&t2, nullptr, getTicket, (void *)"thread 2");
    pthread_create(&t3, nullptr, getTicket, (void *)"thread 3");
    pthread_create(&t4, nullptr, getTicket, (void *)"thread 4");

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);
*/
    std::unique_ptr<Thread> thread1(new Thread(getTicket,(void*)"user1",1));
    std::unique_ptr<Thread> thread2(new Thread(getTicket,(void*)"user2",2));
    std::unique_ptr<Thread> thread3(new Thread(getTicket,(void*)"user3",3));
    std::unique_ptr<Thread> thread4(new Thread(getTicket,(void*)"user4",4));

    thread1->join();
    thread2->join();
    thread3->join();
    thread4->join();


    return 0;
}







